package com.bjpowernode.dataservice.service;

import ch.qos.logback.core.util.TimeUtil;
import com.bjpowernode.api.model.BidInfo;
import com.bjpowernode.api.model.FinanceAccount;
import com.bjpowernode.api.model.Income;
import com.bjpowernode.api.model.Product;
import com.bjpowernode.api.serivce.IncomeService;
import com.bjpowernode.constants.Constant;
import com.bjpowernode.dataservice.mapper.BidInfoMapper;
import com.bjpowernode.dataservice.mapper.FinanceAccountMapper;
import com.bjpowernode.dataservice.mapper.IncomeMapper;
import com.bjpowernode.dataservice.mapper.ProductMapper;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.management.MonitorInfo;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author 麦翔盛
 * @ClassName: IncomeServiceImpl
 * @Package: com.bjpowernode.dataservice.service
 * @description: 收益服务接口
 * @date 2022/5/28 21:46
 */
@DubboService(interfaceClass = IncomeService.class,version = "1.0")
public class IncomeServiceImpl implements IncomeService {
    @Resource
    ProductMapper productMapper;

    @Resource
    BidInfoMapper bidInfoMapper;

    @Resource
    IncomeMapper incomeMapper;

    @Resource
    FinanceAccountMapper financeAccountMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void generateIncomePlan() {
        //获取产生收益的区间 [前一天0:00 今天0:00)
        Date curDate = new Date();
        //通过工具类构造时间区间
        //昨天0:00 (今天-1)截断日后面的时间(变为0:00)
        Date beginDate = DateUtils.truncate(DateUtils.addDays(curDate,-1), Calendar.DATE);
        Date endDate = DateUtils.truncate(curDate,Calendar.DATE);

        //获取时间区间内已经满标的产品
        List<Product> manBiaoList = productMapper.selectManBiaoList(beginDate,endDate);


        Integer productId = null, cycle = null, productType = null;
        BigDecimal dateRate = null, incomeMoney = null;
        Date productFullTime = null, incomeDate = null;
        //遍历满标产品产生收益
        for (Product product : manBiaoList) {
            //获取产品id
            productId = product.getId();
            //获取产品周期
            cycle = product.getCycle();
            //获取产品类型
            productType = product.getProductType();
            //获取满标时间
            productFullTime = product.getProductFullTime();
            //计算日利率(保留十位小数 防止金额过小 )
            dateRate = product.getRate()
                    .divide(new BigDecimal(360),10, RoundingMode.HALF_UP)
                    .divide(new BigDecimal(100),10,RoundingMode.HALF_UP);
            //查询投资了这个产品的用户
            List<BidInfo> bidInfoList = bidInfoMapper.selectAllProductByPid(productId);

            for (BidInfo bidInfo : bidInfoList) {
                //计算产品的利息 计算公式: 利息 = 本金 * 日利率 * 周期(日)
                //获取到期的日期 计算公式: 日期 = 满标时间 + 1 + 周期(日)
                if (productType == Constant.PRODUCT_TYPE_X){
                    //以日为单位的投资计算
                    incomeDate = DateUtils.addDays(productFullTime,cycle + 1);
                    incomeMoney = bidInfo.getBidMoney().multiply(dateRate).multiply(new BigDecimal(cycle));
                }else{
                    //以月为单位的投资计算
                    incomeDate = DateUtils.addDays(productFullTime,cycle * 30 + 1);
                    incomeMoney = bidInfo.getBidMoney().multiply(dateRate).multiply(new BigDecimal(cycle * 30));
                }

                //创建收益
                Income income = new Income();
                income.setUid(bidInfo.getUid());
                income.setProdId(productId);
                income.setBidId(bidInfo.getId());
                income.setBidMoney(bidInfo.getBidMoney());
                income.setIncomeDate(incomeDate);
                income.setIncomeMoney(incomeMoney);
                income.setIncomeStatus(Constant.INCOME_STATUS_0);
                //放入输入库
                incomeMapper.insertSelective(income);
            }

            //修改这个产品的状态为2
            int rows = productMapper.updateStatus(productId,Constant.PRODUCT_STATUS_2);
            if (rows <= 0){
                throw new RuntimeException("生成收益计划异常，更新产品状态为2失败");
            }
            //生成收益成功
            System.out.println(new Date() + " 生成收益成功! ");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void generateIncomeBack() {
        //查询昨天到期的投资记录
        List<Income> incomeList = incomeMapper.selectExpireIncomeList();

        for (Income income : incomeList) {
            //收益返还到用户账户
            int rows = financeAccountMapper.updateMoneyByUid(income.getUid(),income.getIncomeMoney(),income.getBidMoney());
            if (rows <= 0){
                throw new RuntimeException("收益返还到用户账户失败");
            }
            //修改收益表中的状态
            Income updateIncome = new Income();
            updateIncome.setId(income.getId());
            updateIncome.setIncomeStatus(Constant.INCOME_STATUS_1);
            rows = incomeMapper.updateByPrimaryKeySelective(updateIncome);
            if (rows <= 0){
                throw new RuntimeException("修改投资中的状态失败");
            }
        }
        System.out.println(new Date() + " 收益返还成功 ");
    }
}










